package com.nuoniu.sibanyun.service.erp.in.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nuoniu.sibanyun.common.exception.NuoNiuException;
import com.nuoniu.sibanyun.entity.bo.UsedGradeRuleBo;
import com.nuoniu.sibanyun.entity.erp.in.InInventoryCategory;
import com.nuoniu.sibanyun.mapper.erp.in.InInventoryCategoryMapper;
import com.nuoniu.sibanyun.service.erp.IErpAccountService;
import com.nuoniu.sibanyun.service.erp.IErpGradeRuleService;
import com.nuoniu.sibanyun.service.erp.in.IInInventoryCategoryService;
import com.nuoniu.sibanyun.userThread.UserInfo;
import com.nuoniu.sibanyun.userThread.UserThreadLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 存货分类 服务实现类
 * </p>
 *
 * @author 小啊刚
 * @since 2021-06-12
 */
@Service
public class InInventoryCategoryServiceImpl extends ServiceImpl<InInventoryCategoryMapper, InInventoryCategory> implements IInInventoryCategoryService {

    @Autowired
    private IErpAccountService accountService;
    @Autowired
    private IErpGradeRuleService erpGradeRuleService;

    @Override
    public void updateChildrenParentIds(InInventoryCategory inInventoryCategory, InInventoryCategory parentInventoryCategory) {
        InInventoryCategory inventoryCategory = this.getById(inInventoryCategory.getId());
        if(inventoryCategory.getParentId() != inInventoryCategory.getParentId()) {
            String newTreeNames = parentInventoryCategory.getTreeNames() + "/" + inInventoryCategory.getName();
            String newParentIds = parentInventoryCategory.getParentIds() + parentInventoryCategory.getId() + ",";
            baseMapper.updateChildrenParentIds(inventoryCategory.getId(), inventoryCategory.getParentIds(), inventoryCategory.getTreeNames(), newParentIds, newTreeNames);
        }
    }

    @Override
    public List<InInventoryCategory> getByParentIdList(Long parentId) {
        return baseMapper.getByParentIdList(parentId);
    }

    @Override
    public InInventoryCategory getByCode(InInventoryCategory inInventoryCategory) {
        return baseMapper.getByCode(inInventoryCategory);
    }

    @Override
    public InInventoryCategory getByName(InInventoryCategory inInventoryCategory) {
        return baseMapper.getByName(inInventoryCategory);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void saveInventoryCategory(InInventoryCategory inInventoryCategory) {
        UserInfo userInfo = UserThreadLocal.get();
        inInventoryCategory.setCompanyId(userInfo.getCompanyId());
        InInventoryCategory parentInventoryCategory = this.getById(inInventoryCategory.getParentId());

        InInventoryCategory inventoryCategory = this.getByCode(inInventoryCategory);
        if(inventoryCategory != null && (inInventoryCategory.getId() == null || !(inventoryCategory.getId().equals(inInventoryCategory.getId())))) {
            throw new NuoNiuException("编码已存在");
        }

        InInventoryCategory inventoryCategoryByName = this.getByName(inInventoryCategory);
        if(inventoryCategoryByName != null && (inInventoryCategory.getId() == null || !(inventoryCategoryByName.getId().equals(inventoryCategoryByName.getId())))) {
            throw new NuoNiuException("名称已存在");
        }
        UsedGradeRuleBo usedGradeRuleBo;
        //校验 编码规则
        if(parentInventoryCategory != null) { //校验编码规则
            usedGradeRuleBo = erpGradeRuleService.checkCode(inInventoryCategory.getCode(), parentInventoryCategory.getCode(), parentInventoryCategory.getLevel(), "inventoryCategoryId");
        }else {
            usedGradeRuleBo = erpGradeRuleService.checkCode(inInventoryCategory.getCode(), null, null, "inventoryCategoryId");
        }
        inInventoryCategory.setGradeRuleLevel(usedGradeRuleBo.getGradeRuleLevel());
        inInventoryCategory.setGradeRuleStr(usedGradeRuleBo.getGradeRuleStr());

        if(inInventoryCategory.getId() != null) {
            if(parentInventoryCategory != null && (inInventoryCategory.getId()).equals(parentInventoryCategory.getParentId())) {
                throw new NuoNiuException("上级分类不能选择自己");
            }

            //修改下级的父级ids
            if(parentInventoryCategory != null) {
                inInventoryCategory.setLevel(parentInventoryCategory.getLevel() + 1);
                this.updateChildrenParentIds(inInventoryCategory, parentInventoryCategory);
                inInventoryCategory.setUpdateDate(LocalDateTime.now());
            }else {
                inInventoryCategory.setLevel(1);
            }

            inInventoryCategory.setTreeNames(inInventoryCategory.getName());
            inInventoryCategory.setParentIds("0,");
            inInventoryCategory.setUpdateUserId(userInfo.getUserId());
            inInventoryCategory.setUpdateDate(LocalDateTime.now());

            InInventoryCategory oldCategory = this.getById(inInventoryCategory.getId());
            String newTreeNames = inInventoryCategory.getName() + "/";
            String newParentIds = inInventoryCategory.getId() + ",";
            baseMapper.updateChildrenParentIds(oldCategory.getId(), oldCategory.getParentIds(), oldCategory.getTreeNames() + "/", newParentIds, newTreeNames);
        }else {
            if(parentInventoryCategory != null) {
                inInventoryCategory.setLevel(parentInventoryCategory.getLevel() + 1);
                if (parentInventoryCategory.getParentIds().endsWith(",")) {
                    inInventoryCategory.setParentIds(parentInventoryCategory.getParentIds() + parentInventoryCategory.getId() + ",");
                }else {
                    inInventoryCategory.setParentIds(parentInventoryCategory.getParentIds() + parentInventoryCategory.getId() + ",");
                }
                inInventoryCategory.setTreeNames(parentInventoryCategory.getTreeNames() + "/" + inInventoryCategory.getName());
                //修改父级
                parentInventoryCategory.setIsEndNode(false);
                this.updateById(parentInventoryCategory);
            }else {
                inInventoryCategory.setLevel(1);
                inInventoryCategory.setTreeNames(inInventoryCategory.getName());
            }
            inInventoryCategory.setCreateUserId(userInfo.getUserId());
            Integer currentAccountId = accountService.getCurrentAccountId();
            inInventoryCategory.setAccountId(currentAccountId);
        }
        this.saveOrUpdate(inInventoryCategory);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void deleteById(Integer id) {
        InInventoryCategory inInventoryClass = this.getById(id);
        if(!inInventoryClass.getIsEndNode()) {
            throw new NuoNiuException("只能删除末级");
        }
        this.removeById(id);
        Integer parentId = inInventoryClass.getParentId();
        //判断父级是否末级
        if(parentId != null) {
            List<InInventoryCategory> inventoryCategoryList = this.getByParentIdList(parentId.longValue());
            if(inventoryCategoryList.size() == 0) {
                InInventoryCategory inventoryCategory = new InInventoryCategory();
                inventoryCategory.setId(parentId.longValue());
                inventoryCategory.setIsEndNode(true);
                this.updateById(inventoryCategory);
            }
        }
    }

    @Override
    public void checkUsed(Long id) {

    }

    @Override
    public List<InInventoryCategory> getInventoryCategoryList() {
        UserInfo userInfo = UserThreadLocal.get();
        QueryWrapper<InInventoryCategory> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("company_id", userInfo.getCompanyId());
        queryWrapper.orderByAsc("code");
        return list(queryWrapper);
    }
}
